<template>
  <el-dialog
    :model-value="modelValue"
    :title="imageData ? '编辑图片' : '上传图片'"
    width="800px"
    @close="handleCancel"
  >
    <el-dialog v-model="previewVisible" title="图片预览" width="600px">
      <el-image
        :src="previewUrl"
        :preview-src-list="[previewUrl]"
        fit="contain"
        style="width: 100%; height: 400px"
      />
    </el-dialog>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-form-item v-if="!imageData" label="选择图片" prop="file">
        <el-upload
          ref="uploadRef"
          class="w-full"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          :on-remove="handleRemove"
          list-type="picture-card"
          :multiple="true"
        >
          <el-icon>
            <Plus />
          </el-icon>

          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
          </template>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <el-icon>
                    <zoom-in />
                  </el-icon>
                </span>

                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click.stop="handleCustomRemove(file)"
                >
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="文件名" prop="fileName" v-if="imageData">
        <el-input v-model="form.fileName" placeholder="请输入文件名" />
      </el-form-item>

      <el-form-item label="分类" prop="category">
        <DictSelect v-model="form.category" dict-type="image_category" placeholder="请选择分类" />
      </el-form-item>

      <el-form-item label="标签" prop="tags">
        <DictSelect v-model="form.tags" dict-type="image_tag" placeholder="请选择标签" multiple />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  defineProps,
  defineEmits,
  onBeforeUnmount,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  UploadFilled,
  ZoomIn,
  Download,
  Delete,
  Plus,
} from "@element-plus/icons-vue";
import { uploadImage, updateImageInfo } from "@/api/image";
import DictSelect from "@/components/DictSelect.vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  imageData: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const formRef = ref();
const uploadRef = ref();
const submitLoading = ref(false);
const fileObject = ref(null);
const disabled = ref(false);
const previewVisible = ref(false);
const previewUrl = ref("");

const form = reactive({
  fileList: [],
  fileName: "",
  category: "",
  tags: [],
});

const rules = {};

// 监听imageData变化
watch(
  () => props.imageData,
  (newVal) => {
    if (newVal) {
      form.fileName = newVal.fileName || "";
      form.category = newVal.category;
      form.tags = Array.isArray(newVal.tags) ? [...newVal.tags] : [];
    } else {
      // 重置表单
      form.fileList = [];
      form.category = "";
      form.tags = [];
      fileObject.value = null;
      // 清空上传列表
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    }
  }
);

// 处理文件选择
const handleFileChange = (file, fileList) => {
  // 验证文件类型和大小
  const isImage =
    file.raw.type === "image/jpeg" || file.raw.type === "image/png";
  const isLt2M = file.raw.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传 JPG/PNG 格式的图片!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }

  // 更新文件列表
  form.fileList = fileList.map((f) => f.raw);
  fileObject.value = fileList;

  return true;
};

// 处理删除（el-upload的on-remove事件）
const handleRemove = (file, fileList) => {
  // 确保fileList不为undefined
  const safeFileList = fileList || [];
  fileObject.value = safeFileList;

  // 同步更新本地状态
  form.fileList = safeFileList.map((f) => f.raw);
};

// 处理自定义删除（删除按钮点击）
const handleCustomRemove = (file) => {
  // 从fileObject中移除文件
  if (fileObject.value) {
    const index = fileObject.value.findIndex((f) => f.uid === file.uid);
    if (index > -1) {
      fileObject.value.splice(index, 1);
    }
  }

  // 从form.fileList中移除文件
  if (form.fileList) {
    const index = form.fileList.findIndex((f) => f.uid === file.uid);
    if (index > -1) {
      form.fileList.splice(index, 1);
    }
  }

  // 同步更新uploadRef的内部状态
  if (uploadRef.value && uploadRef.value.uploadFiles) {
    const uploadIndex = uploadRef.value.uploadFiles.findIndex(
      (f) => f.uid === file.uid
    );
    if (uploadIndex > -1) {
      uploadRef.value.uploadFiles.splice(uploadIndex, 1);
    }
  }
};

// 处理取消
const handleCancel = () => {
  // 清空上传列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }

  // 重置表单数据
  form.fileList = [];
  form.category = "";
  form.tags = [];
  fileObject.value = null;

  emit("update:modelValue", false);
};

// 组件卸载前清理上传列表
onBeforeUnmount(() => {
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
});

// 处理图片预览
const handlePictureCardPreview = (file) => {
  previewUrl.value = file.url;
  previewVisible.value = true;
};

// 处理提交
const handleSubmit = async () => {
  // 如果是上传新图片，需要验证文件
  if (!props.imageData && (!form.fileList || form.fileList.length === 0)) {
    ElMessage.error("请选择图片文件");
    return;
  }

  await formRef.value.validate(async (valid) => {
    if (!valid) return;

    submitLoading.value = true;
    try {
      if (props.imageData) {
        // 验证文件名
        if (!form.fileName) {
          ElMessage.error("请输入文件名");
          return;
        }
        // 编辑图片信息
        await updateImageInfo(props.imageData.id, {
          fileName: form.fileName,
          category: form.category,
          tags: form.tags,
        });
        ElMessage.success("图片信息更新成功");
      } else {
        // 批量上传新图片
        const formData = new FormData();
        form.fileList.forEach((file, index) => {
          formData.append(`file`, file);
        });
        formData.append("category", form.category);
        formData.append("tags", JSON.stringify(form.tags));

        await uploadImage(formData);
        ElMessage.success(`成功上传${form.fileList.length}张图片`);
      }

      emit("success");
      handleCancel();
    } catch (error) {
      ElMessage.error(props.imageData ? "图片信息更新失败" : "图片上传失败");
    } finally {
      submitLoading.value = false;
    }
  });
};
</script>

<style scoped>
/* 使用Tailwind CSS替代原有样式 */

/* 优化picture-card样式 */
:deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  margin: 0 8px 8px 0;
  display: inline-flex;
  vertical-align: top;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
  margin: 0 8px 8px 0;
  display: inline-flex;
  vertical-align: top;
}

/* 弹框内容区域样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

/* 上传区域容器样式 */
.w-full {
  display: flex;
  flex-wrap: wrap;
}
</style>